import datetime
import pymysql
import redis
from constant.constant import *
from globals.globals import *

pool = redis.ConnectionPool(host=constant.REDIS_HOST, port=constant.REDIS_PORT, password=constant.REDIS_PASSWORD,
                                 decode_responses=True)

runtime_model_sql = 'select * from equipmentrunmodel;'
with my_session() as session:
    runtimes = session.execute(runtime_model_sql).fetchall()


class RunTimeModel():

    def __init__(self,runtime):
        # 构造模型
        self.ID = runtime.ID
        self.equipmentID = runtime.equipmentID
        self.equipmentcode = runtime.equipmentcode
        self.calc_class = runtime.calc_class
        self.statistical_type = runtime.statistical_type
        self.readredistable = runtime.readredistable
        self.ifconditions = runtime.ifconditions.split(';')
        self.symbol = runtime.symbol.split(';')
        self.condition_relation = runtime.condition_relation
        self.standvalue = runtime.standvalue.split(';')
        self.duration_time = runtime.duration_time
        self.writeredistable = runtime.writeredistable
        self.redistag = runtime.redistag
        self.description = runtime.description

        # 连接对象
        self.r = redis.Redis(connection_pool=pool)

        # 辅助参数
        self.status = 0
        self.runtime = int(float(self.r.hget(self.writeredistable, str(self.equipmentID) + '_runtime'))) if self.r.hget(self.writeredistable, str(self.equipmentID) + '_runtime') else 0
        self.time_counts = 0
        self.start_counts = int(self.r.hget(self.writeredistable, str(self.equipmentID) + '_startcount')) if self.r.hget(self.writeredistable, str(self.equipmentID) + '_startcount') else 0

    # 运行时间、启停次数计算
    def run_time_count(self):
        if self.calc_class == MODEL_MODE_1:
            expression = list(zip(self.ifconditions, self.symbol, self.standvalue))
            result_count = 0
            for exp in expression:
                ifcon = self.r.hget(self.readredistable, exp[0])
                standvalue = exp[2]
                result = operators[exp[1]](ifcon, standvalue) if ifcon else None
                result_count += 1 if result else 0

            # 满足条件则运行时间 += 定时任务时间
            if self.condition_relation == RELATION_1 and result_count == len(expression) or self.condition_relation == RELATION_2 and result_count == 1 or self.condition_relation == None and result_count == 1:
                # 服务重启时取redis运行时间
                if not self.time_counts:
                    self.time_counts = self.runtime * 3600 + RUN_LOOP_TIME
                else:
                    self.time_counts += RUN_LOOP_TIME
                # 写入运行时间 : h
                runtime = int(self.time_counts / 3600) if self.time_counts else 0
                self.r.hmset(self.writeredistable, {
                    str(self.equipmentID) + '_running': 1,
                    str(self.equipmentID) + '_runtime': runtime,
                    str(self.equipmentID) + '_runtime_writetime': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                })
                # 启动跳变处理
                if not self.status:
                    # 设备状态变更
                    self.status = 1
                    self.start_counts += 1
                    self.r.hset(self.writeredistable, str(self.equipmentID) + '_startcount', self.start_counts)
                    self.r.hset(self.writeredistable, str(self.equipmentID) + '_startcount_writetime',
                                datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
            # 设备停机
            else:
                if self.status == 1:
                    self.status = 0
                    self.r.hset(self.writeredistable, str(self.equipmentID) + '_running', 0)

        # else:
        #     # 读取运行时间
        #     runtime = self.r.hget(self.readredistable, self.ifconditions[0])
        #     # 对比产生变化则写入运行时间 ，更新运行时间值
        #     if self.runtime != runtime:
        #         self.r.hmset(self.writeredistable, {
        #             str(self.equipmentID) + '_running': 1,
        #             str(self.equipmentID) + '_runtime': self.runtime,
        #             str(self.equipmentID) + '_runtime_writetime': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
        #                       })
        #         self.runtime = runtime
        #     else:
        #         self.r.hset(self.writeredistable, str(self.equipmentID) + '_running', 0)

runtime_models = list()
def get_runtime_model():
    '''
    构造运行时间、启停次数模型列表
    '''
    for runtime in runtimes:
        runtime_models.append(RunTimeModel(runtime))

get_runtime_model()


def runtime_job():
    for model in runtime_models:
        model.run_time_count()

